package com.wffz.websocket;


import com.wffz.config.websocket.ServerDataEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.security.Principal;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author sunlei
 * @className MyWebSocket
 * @Description
 * @date 2023-02-18 9:37
 **/
@ServerEndpoint(value = "/ws_bet", encoders = {ServerDataEncoder.class})
@Component
@Slf4j
public class BetSocket {


    private static int onlineCount = 0;


    private static CopyOnWriteArraySet<BetSocket> webSocketSet = new CopyOnWriteArraySet<BetSocket>();


    private Session session;


    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        Principal p = session.getUserPrincipal();
        log.info("---------------------：" + p.getName());
        webSocketSet.add(this);
        addOnlineCount();
        log.info("有新连接加入！当前在线人数为" + getOnlineCount());
        try {
            log.info("连接已建立成功.");
        } catch (Exception e) {
            log.error("IO异常");
        }
    }


    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        subOnlineCount();
        log.info("有一连接关闭！当前在线人数为" + getOnlineCount());

    }


    @OnMessage
    public void onMessage(String message, Session session) {
        log.info("来自客户端的消息:" + message);
    }


    @OnError
    public void onError(Session session, Throwable error) {

        log.info("发生错误");

        error.printStackTrace();

    }


    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }

    public void sendObjMessage(Object o) throws EncodeException, IOException {
        this.session.getBasicRemote().sendObject(o);
    }


    public static synchronized int getOnlineCount() {
        return onlineCount;

    }


    public static synchronized void addOnlineCount() {
        BetSocket.onlineCount++;

    }


    public static synchronized void subOnlineCount() {
        BetSocket.onlineCount--;

    }


    public Session getSession() {
        return session;

    }


    public void setSession(Session session) {
        this.session = session;
    }


    public static CopyOnWriteArraySet<BetSocket> getWebSocketSet() {
        return webSocketSet;

    }


    public static void setWebSocketSet(CopyOnWriteArraySet<BetSocket> webSocketSet) {
        BetSocket.webSocketSet = webSocketSet;

    }

}